import tushare as ts

token = 'bc5fc00fe9b49bcd208c851d7738692a2bfca04400c29e3a451ffdb6'

token2 = 'ea5c180841549a4667eb15c856650b011f4925c4b0cf1d963f297c67'

def get_realtime_boxoffice():
    df = ts.realtime_boxoffice()

    return df.to_dict(orient='record')

def get_month_boxoffice(date=None):
    if date:
        df = ts.month_boxoffice(date)
    else:
        df = ts.month_boxoffice()
    return df.to_dict(orient='record')


def get_day_boxoffice(date=None):
    if date:
        df = ts.day_boxoffice(date)
    else:
        df = ts.day_boxoffice()
    return df.to_dict(orient='record')




def get_ppi(topN=10):
    """
    工业品出厂价格指数
    :return: 
    """
    keys = {
        "month":"统计月份",
        "ppiip":"工业品出厂价格指数",
        "ppi":"生产资料价格指数",
        "qm":"采掘工业价格指数",
        "rmi":"原材料工业价格指数",
        "pi":"加工工业价格指数",
        "cg":"生活资料价格指数",
        "food":"食品类价格指数",
        "clothing":"衣着类价格指数",
        "roeu":"一般日用品价格指数",
        "dcg":"耐用消费品价格指数"}
    df = ts.get_ppi()
    df =  df.rename(columns=keys)
    return df[:topN].to_dict(orient='record')

def get_rrr(topN=10):
    """
    存款准备金率
    :return: 
    """
    keys = {
        "date": "变动日期",
        "before": "调整前存款准备金率(%)",
        "now": "调整后存款准备金率(%)",
        "changed": "调整幅度(%)",
    }
    df = ts.get_rrr()
    df = df.rename(columns=keys)
    return df[:topN].to_dict(orient='record')


def use_pro_api():
    pro = ts.pro_api(token2)
    df = pro.stock_basic()
    print(df.head())

# 天气
import requests
import json
from random import randint
from datetime import datetime
class QueryWeather:
    def __init__(self, query_city, query_days):
        self.__appid = '33114491'  # 修改为你的用户 ID
        self.__appsecret = 'MAeeQu6U'  # 修改为你的用户 密钥
        self.param_dict = {'day': '日期:\t', 'week': '星期:\t', 'wea': '天气:\t', 'tem': '温度:\t', 'tem1': '高温:\t', 'tem2': '低温:\t', 'win': '风向:\t', 'win_speed': '风速:\t', 'air_level': '空气:\t', 'air_tips': '建议:\t'}
        self.city = query_city
        self.query_days = query_days
        self.url = f"https://www.tianqiapi.com/api/?version=v1&city=" \
                   f"{self.city}&appid={self.__appid}&appsecret={self.__appsecret}"
        self.result = self.get()

    def get(self):
        ret = requests.get(self.url)
        ret.encoding = 'utf-8'
        result = json.loads(ret.text)
        return result

    def show(self):
        self.__show_info()
        for i in range(self.query_days):
            for key, val in self.param_dict.items():
                if (i > 0) and (key is 'air_level'):
                    pass
                elif (i > 0) and (key is 'air_tips'):
                    pass
                else:
                    weather_info = str(val) + str(self.result['data'][i][key])
                    print(weather_info)
            print("-"*40)

    def __show_info(self):
        print("国家: %s\n城市: %s\n更新时间: %s" %
              (self.result['country'], self.result['city'], self.result['update_time']))
        print(self.result['city'] + "最近%d天的天气情况如下: " % self.query_days)
        print("-"*40)

# 旅游假数据 - 每天接待游客人数，支付方式比例

import arrow


def isLeapYear(years):
    '''
    通过判断闰年，获取年份years下一年的总天数
    :param years: 年份，int
    :return:days_sum，一年的总天数
    '''
    # 断言：年份不为整数时，抛出异常。
    assert isinstance(years, int), "请输入整数年，如 2018"

    if ((years % 4 == 0 and years % 100 != 0) or (years % 400 == 0)):  # 判断是否是闰年
        # print(years, "是闰年")
        days_sum = 366
        return days_sum
    else:
        # print(years, '不是闰年')
        days_sum = 365
        return days_sum


def getAllDayPerYear(years, days_sum=0):
    '''
    获取一年的所有日期
    :param years:年份
    :return:全部日期列表
    '''
    start_date = '%s-1-1' % years
    a = 0
    all_date_list = []
    if days_sum <= 0:
        days_sum = isLeapYear(int(years-1))

    while a < days_sum:
        b = arrow.get(start_date).shift(days=a)
        a += 1
        all_date_list.append(b)
    # print(all_date_list)
    return all_date_list


def is_weekend(date):
    return date.isoweekday() == "0" or date.isoweekday() == "6"

def tour_data(year):
    viewpoints = ['皂幕山', '盈香生态园', '美的鹭湖森林度假区', '泰康山生态旅游区']
    pay_methods =[('现金', (1, 4)), ('信用卡',(1,4)), ('微信',(5, 8)), ('支付宝',(7, 10)), ('其他', (10, 10))]
    # 旺季
    hot_start = arrow.get('%d-06-20' % year, 'YYYY-MM-DD')
    hot_1 = arrow.get('%d-07-07' % year, 'YYYY-MM-DD')
    hot_2 = arrow.get('%d-08-30' % year, 'YYYY-MM-DD')

    hot_3_1 = arrow.get('%d-10-01' % year, 'YYYY-MM-DD')
    hot_3_2 = arrow.get('%d-10-07' % year, 'YYYY-MM-DD')

    hot_4_1 = arrow.get('%d-05-01' % year, 'YYYY-MM-DD')
    hot_4_2 = arrow.get('%d-05-04' % year, 'YYYY-MM-DD')

    hot_5_1 = arrow.get('%d-02-06' % year, 'YYYY-MM-DD')
    hot_5_2 = arrow.get('%d-02-10' % year, 'YYYY-MM-DD')

    begin = datetime.strptime("%d-01-01" % year, "%Y-%m-%d")
    end = datetime.today()
    days_sum = (end - begin).days - 10
    date_list = getAllDayPerYear(year, days_sum)
    content = []
    all_pie = []
    for point in  viewpoints:

        data = {
            'pay_data': [],
            'daily_visit': [],
        }

        total = 0
        for date_v in date_list:

            if is_weekend(date_v):
                today_count = randint(1000,5000)
            else:
                today_count = randint(600,4000)

            if date_v.is_between(hot_start, hot_1):
                today_count = randint(2000,10000)
            elif date_v.is_between(hot_start, hot_2):
                today_count = randint(2500, 12000)
            elif date_v.is_between(hot_3_1, hot_3_2):
                today_count = randint(2800, 8000)
            elif date_v.is_between(hot_4_1, hot_4_2):
                today_count = randint(3000, 9000)
            elif date_v.is_between(hot_5_1, hot_5_2):
                today_count = randint(3000, 10000)

            total += today_count
            data['daily_visit'].append([date_v.format("YYYY-MM-DD"), today_count])

        # 总和*比例
        rest = total
        all_pie.append({
            'name': point,
            'value': total
        })
        for method in pay_methods:
            rate = randint(method[1][0], method[1][1]) / 10
            val = int(rate * rest)
            data['pay_data'].append({
                'name': method[0],
                'value': val
            })
            rest = rest - val

        content.append(
            [point, data]
        )

    return content, all_pie

if __name__ == "__main__":
    print(tour_data(2019))

    # city = '高明'
    # days = 3
    # query = QueryWeather(city, days)
    # print(query.get())
